package kevin.hbase.analyse.stop;

import kevin.hbase.service.StopService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

@Slf4j
@Component
public class StopManager {
    private int handlerNum = 16;

    private boolean running = false;

    @Autowired
    private StopService stopService;

    private List<StopHandler> handlers = new ArrayList<>();

    private StopHandler getHandler(int index) {
        return handlers.get(index);
    }

    public void deliverToHandler(Map<String, Object> map) {
        int threadIndex = Math.abs(map.get("deviceId").toString().hashCode()) % handlerNum;
        getHandler(threadIndex).addMap(map);
    }


    public boolean isRunning() {
        return running == true;
    }

    public void start() {
        try {
            if (!running) {
                running = true;
                CountDownLatch latch = new CountDownLatch(handlerNum);
                new Thread(() -> {
                    long start1 = System.currentTimeMillis();
                    try {
                        latch.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    long end1 = System.currentTimeMillis();
                    log.info("all StopHandler exec finished ,cost(ms): {}", end1 - start1);
                    handlers.clear();
                    running = false;
                }).start();

                for (int i = 0; i < handlerNum; i++) {
                    StopHandler stopHandler = new StopHandler(i, stopService, latch);
                    handlers.add(stopHandler);
                }

                List<Map<String, Object>> stopDeviceList = stopService.getStopDeviceList();
                log.info("total stopDeviceList size:{}", stopDeviceList.size());
                for (Map<String, Object> device : stopDeviceList) {
                    deliverToHandler(device);
                }

                for (StopHandler stopHandler : handlers) {
                    stopHandler.start();
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

}
